package com.cai.dao.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.cai.dao.DbUtil;
import com.cai.dao.DetailedTopicDao;
import com.cai.pojo.DetailedTopic;
import com.cai.pojo.Topic;
import com.cai.pojo.UserDetailedTopicData;
import com.cai.util.DateUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author RuoLi
 */
public class DetailedTopicDaoImpl implements DetailedTopicDao {
    DbUtil util = new DbUtil();
    static String topicId = null;
    static String detailedTopicId = null;

    @Override
    @SuppressWarnings("unchecked")
    public String getDetailedTopicData(int currentPage, int pageSize) {
        //服务端题目详细信息
        String sql = "CALL show_page_tables(?,?)";
        JSONArray jsonArray = new JSONArray();
        List<DetailedTopic> list = (List<DetailedTopic>) DbUtil.getDetailedTopicPageData(sql, currentPage, pageSize);
        try {
            for (DetailedTopic topic :
                    list) {
                JSONObject jsonObject = new JSONObject();
                jsonTopic(jsonObject, topic);
                jsonArray.add(jsonObject);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonArray.toString();
    }

    @Override
    @SuppressWarnings("unchecked")
    public String getDetailedTopicInfoUserClient(int currentPage, int pageSize) {
        //客户端题目展示
        String sql = "CALL show_userClient_TopicInfo(?,?)";
        JSONArray jsonArray = new JSONArray();
        List<DetailedTopic> list = (List<DetailedTopic>) DbUtil.getDetailedTopicPageDataUserClient(sql, currentPage, pageSize);
        try {
            for (DetailedTopic topic :
                    list) {
                JSONObject jsonObject = new JSONObject();
                jsonTopicUseClient(jsonObject, topic);
                jsonArray.add(jsonObject);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonArray.toString();
    }

    @Override
    public int deleteDetailedTopic(int detailedTopicId) {
        int count = -1;
        String sql = "DELETE FROM `online_quiz_website`.`detailed_topic` WHERE `detailed_topic_id` = ?";
        String[] params = {String.valueOf(detailedTopicId)};
        count = DbUtil.updateContent(sql, params);
        return count;
    }

    @Override
    public String getDetailedTopicPageData(int currentPage, int pageSize) {
        String sql = "CALL count_pages(?)";
        //获取总页数
        int totalPage = DbUtil.getTotalPages(sql, pageSize);
        //获取题目数量
        int totalSize = getCountDetailedTopicTotalSizeData();
        JSONObject jsonPage = new JSONObject();
        jsonPage.put("currentPage", currentPage);
        jsonPage.put("totalPage", totalPage);
        jsonPage.put("pageSize", pageSize);
        jsonPage.put("totalSize", totalSize);
        return jsonPage.toJSONString();
    }

    @Override
    public String getDetailedTopicChoseTopicType(int pageSize, String topicType) {
        String sql = "select ceiling((count(0) / ?)) AS total FROM detailed_topic,topic WHERE topic.topic_type=? AND topic.topic_id=detailed_topic.topic_id";
        String sqlTotalSize = "SELECT count(*) FROM `online_quiz_website`.`detailed_topic`,topic where topic.topic_type= '" + topicType + "' AND topic.topic_id=detailed_topic.topic_id";
        DbUtil dbUtil = new DbUtil();
        String total = dbUtil.selectContent(sql, new String[]{String.valueOf(pageSize), topicType});
        int totalSize = Integer.parseInt(util.selectContent(sqlTotalSize));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("totalPage", total);
        jsonObject.put("pageSize", pageSize);
        jsonObject.put("totalSize", totalSize);
        return jsonObject.toString();
    }

    @Override
    public int getCountDetailedTopicTotalSizeData() {
        int count = -1;
        String sql = "SELECT count(*) FROM `online_quiz_website`.`detailed_topic` ";
        count = Integer.parseInt(util.selectContent(sql));
        return count;
    }

    @Override
    @SuppressWarnings("unchecked")
    public String getDetailedTopicData(int detailedTopicId) {
        String sql = "SELECT * FROM topic,detailed_topic WHERE topic.topic_id=detailed_topic.topic_id AND detailed_topic.detailed_topic_id=?";
        String[] params = {String.valueOf(detailedTopicId)};
        List<DetailedTopic> list = (List<DetailedTopic>) DbUtil.getDetailedTopicData(sql, params);
        JSONObject json = new JSONObject();
        for (DetailedTopic topic : list
        ) {
            jsonTopic(json, topic);
        }
        return json.toString();
    }

    @Override
    public int updateDetailedTopicData(Map<String, String[]> map) {
        String type1 = "填空题";
        String type2 = "选择题";
        String topicCheck1 = "";
        String topicCheck2 = "";
        String topicCheck3 = "";
        String topicCheck4 = "";
        int count = -1;
        String sql = "UPDATE detailed_topic,topic " +
                "SET " +
                "grade=?,chapter_name=?,knowledge_point=?,topic_type=?,topic_title=?,topic_check_1=?,topic_check_2=?,topic_check_3=?,topic_check_4=?,topic_answer=?,topic_answer_parse=? " +
                "WHERE " +
                "topic.topic_id=detailed_topic.topic_id " +
                "AND " +
                "detailed_topic_id = ?";
        //解析map数据

        String topicType = map.get("topicType")[0];
        //如果是填空题
        String grade = map.get("topicGrade")[0];
        String chapterName = map.get("topicChapterName")[0];
        String knowledgePoint = map.get("topicKnowledgePoint")[0];
        String topicTitle = map.get("topicTitle")[0];
        String topicAnswer = map.get("topicAnswer")[0];
        String topicAnswerParse = map.get("topicAnswerParse")[0];
        String detailedTopicId = map.get("topicDetailedId")[0];
        //选择
        if (type2.equals(topicType)) {
            topicCheck1 = map.get("topicCheck1")[0];
            topicCheck2 = map.get("topicCheck2")[0];
            topicCheck3 = map.get("topicC1heck3")[0];
            topicCheck4 = map.get("topicCheck4")[0];
            String[] params = {grade, chapterName, knowledgePoint, topicType, topicTitle, topicCheck1, topicCheck2, topicCheck3, topicCheck4, topicAnswer, topicAnswerParse, detailedTopicId};
            count = DbUtil.updateContent(sql, params);
            //填空
        } else if (type1.equals(topicType)) {
            String[] params = {grade, chapterName, knowledgePoint, topicType, topicTitle, topicCheck1, topicCheck2, topicCheck3, topicCheck4, topicAnswer, topicAnswerParse, detailedTopicId};
            count = DbUtil.updateContent(sql, params);
        } else {
            //判断
            topicCheck1 = map.get("topicCheck1")[0];
            topicCheck2 = map.get("topicCheck2")[0];
            String[] params = {grade, chapterName, knowledgePoint, topicType, topicTitle, topicCheck1, topicCheck2, topicCheck3, topicCheck4, topicAnswer, topicAnswerParse, detailedTopicId};
            count = DbUtil.updateContent(sql, params);
        }
        return count;
    }

    @Override
    public int insertTopicData(Map<String, String[]> map) {
        String newTopicId = null;
        //获取当前TopicId最大id
        String sqlTopic = "select max(topic_id) from topic";
        String sqlInsertTopic = "INSERT INTO " +
                "topic" +
                "(topic_id, subject_name, grade, chapter_name, knowledge_point, topic_type) " +
                "VALUES (?,?,?,?,?,?)";
        String maxTopicId = util.selectContent(sqlTopic);
        String maxTopicId1 = maxTopicId.substring(0, 5);
        String maxTopicId2 = maxTopicId.substring(5, 8);
        if (maxTopicId1.equals(DateUtil.getDate().substring(3, 8))) {
            int lastId = Integer.parseInt(maxTopicId2) + 1;
            newTopicId = maxTopicId1 + lastId;
        } else {
            int lastId = 100;
            newTopicId = DateUtil.getDate().substring(3, 8) + lastId;

        }
        topicId = newTopicId;
        String[] paramsTopic = {
                newTopicId, "数学", map.get("grade")[0],
                map.get("chapterName")[0], map.get("knowledgePoint")[0],
                map.get("topicType")[0]
        };
        return DbUtil.updateContent(sqlInsertTopic, paramsTopic);
    }

    @Override
    public String getAfterInsertTopicId() {
        JSONObject object = new JSONObject();
        object.put("topicId", topicId);
        object.put("detailedTopicId", detailedTopicId);
        return object.toString();
    }

    @Override
    @SuppressWarnings("unchecked")
    public String getKnowledgePointTabsInfo() {
        String sql = "SELECT DISTINCT knowledge_point FROM topic GROUP BY knowledge_point;";
        List<Topic> list = (List<Topic>) DbUtil.getTopicKnowledgePointData(sql);
        JSONArray jsonArray = new JSONArray();
        for (Topic topic : list
        ) {
            JSONObject json = new JSONObject();
            json.put("topicKnowledgePoint", topic.getKnowledge_point());
            jsonArray.add(json);
        }
        return jsonArray.toString();
    }

    @Override
    @SuppressWarnings("unchecked")
    public String getUserDetailedTopicInfo(int detailedTopicId) {
        String sql = "SELECT subject_name,grade,chapter_name,knowledge_point,topic_type," +
                "detailed_topic_id,topic_title,topic_check_1,topic_check_2,topic_check_3,topic_check_4,topic_check_5,frequency " +
                "FROM topic,detailed_topic " +
                "WHERE topic.topic_id=detailed_topic.topic_id AND detailed_topic_id=?";
        List<UserDetailedTopicData> list = (List<UserDetailedTopicData>) DbUtil.getUserDetailedTopicData(sql, detailedTopicId);
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        for (UserDetailedTopicData userDetailedTopicData : list
        ) {
            jsonUserDetailedTopicData(json, userDetailedTopicData);
            jsonArray.add(json);
        }
        return jsonArray.toString();
    }

    @Override
    @SuppressWarnings("unchecked")
    public String getRandomTopicCount5() {
        String sql = "SELECT subject_name,grade,chapter_name,knowledge_point,topic_type," +
                "detailed_topic_id,topic_title,topic_check_1,topic_check_2,topic_check_3,topic_check_4,topic_check_5,frequency  " +
                "FROM topic,detailed_topic " +
                "WHERE topic.topic_id=detailed_topic.topic_id " +
                "ORDER BY RAND() LIMIT 5";
        List<UserDetailedTopicData> list = (List<UserDetailedTopicData>) DbUtil.getUserRandomDetailedTopicData(sql);
        JSONArray jsonArray = new JSONArray();
        for (UserDetailedTopicData userDetailedTopicData : list
        ) {
            JSONObject json = new JSONObject();
            jsonUserDetailedTopicData(json, userDetailedTopicData);
            jsonArray.add(json);
        }
        return jsonArray.toString();
    }


    @Override
    @SuppressWarnings("unchecked")
    public String getUserDetailedTopicAnswer(int detailedTopicId) {
        String sql = "SELECT topic_answer,topic_answer_parse FROM detailed_topic WHERE detailed_topic_id=?";
        DbUtil dbUtil = new DbUtil();
        List<DetailedTopic> list = (List<DetailedTopic>) dbUtil.selectContent(sql, new String[]{String.valueOf(detailedTopicId)}, DetailedTopic.class);
        JSONObject jsonObject = new JSONObject();
        for (DetailedTopic topic : list
        ) {
            jsonObject.put("topicAnswer", topic.getTopic_answer());
            jsonObject.put("topicAnswerParse", topic.getTopic_answer_parse());
        }
        return jsonObject.toString();
    }

    @Override
    public int checkUserDetailedTopicAnswer(int detailedTopicId, String answer) {
        String sql = "SELECT count(*) FROM detailed_topic WHERE detailed_topic_id=? AND topic_answer=?";
        String[] params = {String.valueOf(detailedTopicId), answer};
        return DbUtil.selectCountIsExist(sql, params);
    }

    @Override
    @SuppressWarnings("unchecked")
    public String getDetailedTopicInfoUserClientChangeTopicType(String topicType, int currentPage, int pageSize) {
        String sql = "SELECT knowledge_point,detailed_topic_id,topic_title,topic_type,frequency FROM topic,detailed_topic WHERE topic_type=? AND topic.topic_id=detailed_topic.topic_id limit ?,?";
        List<DetailedTopic> list = (List<DetailedTopic>) DbUtil.getDetailedTopicPageDataChoseChange(sql, topicType, currentPage, pageSize);
        JSONArray jsonArray = new JSONArray();
        for (DetailedTopic topic : list
        ) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("topicDetailedId", topic.getDetailed_topic_id());
            jsonObject.put("topicTitle", topic.getTopic_title());
            jsonObject.put("topicKnowledgePoint", topic.getTopic().getKnowledge_point());
            jsonObject.put("topicFrequency", topic.getFrequency());
            jsonObject.put("topicType", topic.getTopic().getTopic_type());
            jsonArray.add(jsonObject);
        }
        return jsonArray.toString();
    }

    @Override
    @SuppressWarnings("unchecked")
    public String getUserSelectData(String select) {
        String data1 = "chapter_name";
        String data2 = "knowledge_point";
        String sql = "SELECT DISTINCT " + select + " FROM topic ;";
        DbUtil dbUtil = new DbUtil();
        List<Topic> list = (List<Topic>) dbUtil.selectContent(sql, new String[]{}, Topic.class);
        JSONObject jsonObject = new JSONObject();
        if (data1.equals(select)) {
            JSONArray jsonArray = new JSONArray();
            for (Topic topic : list
            ) {
                JSONObject json = new JSONObject();
                json.put("key", topic.getChapter_name());
                json.put("value", topic.getChapter_name());
                jsonArray.add(json);
            }
            jsonObject.put(data1, jsonArray);
        }
        if (data2.equals(select)) {
            JSONArray jsonArray = new JSONArray();
            for (Topic topic : list
            ) {
                JSONObject json = new JSONObject();
                json.put("key", topic.getKnowledge_point());
                json.put("value", topic.getKnowledge_point());
                jsonArray.add(json);
            }
            jsonObject.put(data2, jsonArray);
        }
        return jsonObject.toString();
    }

    @Override
    @SuppressWarnings("unchecked")
    public String getMatchKnowledgePoint(String chapterName) {
        String sql = "SELECT DISTINCT knowledge_point FROM topic WHERE chapter_name= '" + chapterName + "';";
        DbUtil dbUtil = new DbUtil();
        List<Topic> list = (List<Topic>) dbUtil.selectContent(sql, new String[]{}, Topic.class);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for (Topic topic : list
        ) {
            JSONObject json = new JSONObject();
            json.put("key", topic.getKnowledge_point());
            json.put("value", topic.getKnowledge_point());
            jsonArray.add(json);
        }
        jsonObject.put("knowledge_point", jsonArray);
        return jsonObject.toString();
    }

    @Override
    @SuppressWarnings("unchecked")
    public String getTopicFromDetailedTopicId(int detailedTopicId) {
        String sql = "SELECT knowledge_point,topic_type,detailed_topic_id,topic_title,frequency FROM topic,detailed_topic WHERE topic.topic_id=detailed_topic.topic_id AND detailed_topic_id like '%" + detailedTopicId + "%' ";
        List<DetailedTopic> list = (List<DetailedTopic>) DbUtil.getUserTopicFromDetailedTopicId(sql);
        System.out.println("模糊查询题库题目数量："+list.size());
        JSONArray jsonArray = new JSONArray();
        for (DetailedTopic topic : list
        ) {
            JSONObject jsonObject = new JSONObject();
            jsonTopicUseClient(jsonObject, topic);
            jsonArray.add(jsonObject);
        }
        System.out.println("模糊题目信息："+jsonArray);
        return jsonArray.toString();
    }

    @Override
    public int insertDetailedTopicData(Map<String, String[]> map) {
        //获取当前detailedTopicId最大id
        String newDetailedTopicId;
        String sqlDetailedTopic = "select max(detailed_topic_id) from detailed_topic";
        String sqlInsertDetailedTopic = "INSERT INTO " +
                "detailed_topic" +
                "(detailed_topic_id, topic_id, topic_title, topic_check_1, topic_check_2, topic_check_3, topic_check_4, topic_answer, topic_answer_parse) " +
                "VALUES (?,?,?,?,?,?,?,?,?)";
        String maxDetailedTopicId = util.selectContent(sqlDetailedTopic);
        String maxDetailedTopicId1 = maxDetailedTopicId.substring(0, 6);
        String maxDetailedTopicId2 = maxDetailedTopicId.substring(6, 9);

        if (maxDetailedTopicId1.equals(DateUtil.getDate().substring(2, 8))) {
            int lastId = Integer.parseInt(maxDetailedTopicId2) + 1;
            newDetailedTopicId = maxDetailedTopicId1 + lastId;
        } else {
            int lastId = 100;
            newDetailedTopicId = DateUtil.getDate().substring(2, 8) + lastId;
        }
        detailedTopicId = newDetailedTopicId;
        String[] paramsDetailedTopic = {
                newDetailedTopicId, topicId, map.get("topicTitle")[0],
                map.get("topicCheck1")[0], map.get("topicCheck2")[0],
                map.get("topicCheck3")[0], map.get("topicCheck4")[0],
                map.get("topicAnswer")[0], map.get("topicAnswerParse")[0]
        };
        return DbUtil.updateContent(sqlInsertDetailedTopic, paramsDetailedTopic);
    }

    /**
     * 将Object封装json
     *
     * @param json  json格式
     * @param topic DetailedTopic Object
     */
    private void jsonTopic(JSONObject json, DetailedTopic topic) {
        json.put("topicDetailedId", topic.getDetailed_topic_id());
        json.put("topicId", topic.getTopic_id());
        json.put("topicTitle", topic.getTopic_title());
        json.put("topicCheck1", topic.getTopic_check_1());
        json.put("topicCheck2", topic.getTopic_check_2());
        json.put("topicCheck3", topic.getTopic_Check_3());
        json.put("topicCheck4", topic.getTopic_check_4());
        json.put("topicCheck5", topic.getTopic_check_5());
        json.put("topicAnswer", topic.getTopic_answer());
        json.put("topicAnswerParse", topic.getTopic_answer_parse());
        json.put("topicFrequency", topic.getFrequency());
        json.put("topicSubjectName", topic.getTopic().getSubject_name());
        json.put("topicGrade", topic.getTopic().getGrade());
        json.put("topicChapterName", topic.getTopic().getChapter_name());
        json.put("topicKnowledgePoint", topic.getTopic().getKnowledge_point());
        json.put("topicType", topic.getTopic().getTopic_type());
    }

    private void jsonTopicUseClient(JSONObject json, DetailedTopic topic) {
        json.put("topicDetailedId", topic.getDetailed_topic_id());
        json.put("topicTitle", topic.getTopic_title());
        json.put("topicKnowledgePoint", topic.getTopic().getKnowledge_point());
        json.put("topicFrequency", topic.getFrequency());
        json.put("topicType", topic.getTopic().getTopic_type());
    }

    private void jsonUserDetailedTopicData(JSONObject json, UserDetailedTopicData userDetailedTopicData) {
        json.put("subject_name", userDetailedTopicData.getSubject_name());
        json.put("grade", userDetailedTopicData.getGrade());
        json.put("chapter_name", userDetailedTopicData.getChapter_name());
        json.put("knowledge_point", userDetailedTopicData.getKnowledge_point());
        json.put("topic_type", userDetailedTopicData.getTopic_type());
        json.put("detailed_topic_id", userDetailedTopicData.getDetailed_topic_id());
        json.put("topic_title", userDetailedTopicData.getTopic_title());
        json.put("topic_check_1", userDetailedTopicData.getTopic_check_1());
        json.put("topic_check_2", userDetailedTopicData.getTopic_check_2());
        json.put("topic_check_3", userDetailedTopicData.getTopic_check_3());
        json.put("topic_check_4", userDetailedTopicData.getTopic_check_4());
        json.put("topic_check_5", userDetailedTopicData.getTopic_check_5());
        json.put("frequency", userDetailedTopicData.getFrequency());
    }

}
